﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NReader.Service.RGS;

namespace NReader.Service
{
    public class GlobalService
    {
        private const int RankFlag = 2001;

        private const int HotFlag = 2002;

        private const int CommendFlag = 2003;

        private const int SIZE_UPDATE_COUNT = 18;

        private const int CompleteFlag = 2005;

        public static GlobalService _globalService;

        public static GlobalService Instance()
        {
            return _globalService ?? (_globalService = new GlobalService());
        }

        public async Task<List<GroupInfoList<object>>> GetIndexGroupList()
        {
            var client = new RemoteGlobalServiceClient();
            //点击排行榜
            //IList<ArticleInfo> rankList = await client.GetGroupListAsync(RankFlag);
            //热点排行榜
            IList<ArticleInfo> hotList = await client.GetGroupListAsync(HotFlag);
            //推荐排行榜
            IList<ArticleInfo> commendList = await client.GetGroupListAsync(CommendFlag);
            //全本排行榜
            IList<ArticleInfo> completeList = await client.GetGroupListAsync(CompleteFlag);
            //最新更新
            IList<ArticleInfo> updateList = await client.GetUpdateListAsync(SIZE_UPDATE_COUNT);
            var groups = new List<GroupInfoList<object>>();
            //AddArticleToGroup(rankList, ref groups);
            AddArticleToGroup(completeList, ref groups);
            AddArticleToGroup(hotList, ref groups);
            AddArticleToGroup(commendList, ref groups);
            AddArticleToGroup(updateList, ref groups);
            return groups;
        }

        private void AddArticleToGroup( IList<ArticleInfo> list,ref List<GroupInfoList<object>> groups)
        {
            var query = from item in list
                        //orderby item.lastupdate
                        group item by item.GroupName
                            into g
                            select new { GroupName = g.Key, Items = g };
            foreach (var g in query)
            {
                var info = new GroupInfoList<object>();
                info.Key = g.GroupName;
                foreach (var item in g.Items)
                {
                    info.Add(item);
                }
                groups.Add(info);
            }
        }
    }

    public class GroupInfoList<T> : List<object>
    {

        public object Key { get; set; }


        public new IEnumerator<object> GetEnumerator()
        {
            return (System.Collections.Generic.IEnumerator<object>)base.GetEnumerator();
        }
    }
}
